import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15

Popup {
    id: numberKeyboard
    width: 700
    height: 780
    modal: true
    closePolicy: Popup.CloseOnPressOutside | Popup.CloseOnEscape
    anchors.centerIn: Overlay.overlay

    property bool isDirectOverwrite: true
    property bool isValueSelected: true  // 手动管理选中状态（核心）
    property string displayText: ""      // 用于Text组件显示的文本

    // 背景样式
    background: Rectangle {
        color: "#ffffff"
        border.color: "#bdc3c7"
        border.width: 3
        radius: 12
    }

    // 样式属性（新增选中状态的视觉样式）
    property string normalColor: "#ffffff"
    property string pressedColor: "#f0f0f0"
    property string hoverColor: "#f8f8f8"
    property string normalBorderColor: "#bdc3c7"
    property string hoverBorderColor: "#3498db"
    property string accentColor: "#FFD700"
    property string accentTextColor: "#2c3e50"
    property string limitTextColor: "#6c757d"
    property string invalidTextColor: "#E53E3E"
    property string displayBackgroundColor: "#f8f9fa"
    property string selectedBackgroundColor: "#f8f9fa"  // 选中状态背景色（模拟选中）
    property real borderWidth: 3
    property real borderRadius: 12
    property real fontPixelSize: 30
    property real displayFontSize: 40
    property string fontColor: "#2c3e50"

    // 输入值和状态管理
    property string currentValue: ""
    property var inputList: []
    property var activeInput: null
    signal confirmed(string value)
    signal cancelled()

    // 注册输入框（保持不变）
    function registerInput(input) {
        if (inputList.indexOf(input) === -1) {
            inputList.push(input);
            setupInputSelection(input);
        }
    }

    // 输入框选中逻辑（保持不变）
    function setupInputSelection(input) {
        input.selectedChanged.connect(function() {
            if (input.isSelected) {
                activeInput = input;
                open();
            }
        });
    }

    // 激活输入框时初始化状态（核心：设置选中状态）
    onActiveInputChanged: {
        if (activeInput) {
            inputList.forEach(function(input) {
                if (input !== activeInput) {
                    input.isSelected = false;
                }
            });
            currentValue = activeInput.text || "0";
            isValueSelected = true;  // 初始为选中状态
            displayText = currentValue;  // 同步到显示文本
        }
    }

    // 弹窗打开时强制选中状态（保持逻辑）
    onOpened: {
        if (activeInput) {
            currentValue = activeInput.text || "0";
            isValueSelected = true;
            displayText = currentValue;
        }
    }

    // 验证值是否在范围内（保持不变）
    function isValidValue(value) {
        if (!activeInput || value === "" || value === "-") return true;
        var num = parseFloat(value);
        if (isNaN(num)) return false;
        return num >= activeInput.minValue && num <= activeInput.maxValue;
    }

    // 获取限制文本（保持不变）
    function getLimitText() {
        if (!activeInput) return "";
        return qsTr("范围: %1 至 %2").arg(activeInput.minValue).arg(activeInput.maxValue);
    }

    // 统一处理数字输入（核心：根据选中状态替换/追加）
    function handleNumberInput(keyText) {
        if (isValueSelected) {
            // 选中状态：直接替换
            currentValue = keyText;
            isValueSelected = false;  // 替换后退出选中状态
        } else {
            // 非选中状态：追加
            currentValue += keyText;
        }
        displayText = currentValue;  // 同步显示
    }

    // 自定义按钮组件（逻辑保持不变）
    component StyledButton: AbstractButton {
        id: styledBtn
        property bool isAccent: false
        property bool isInvalid: false
        property bool isNumberKey: false
        property bool isSymbolKey: false

        width: 640/3
        height: 610/6
        hoverEnabled: true

        background: Rectangle {
            color: styledBtn.isInvalid ? "#FFECEC"
                  : styledBtn.pressed ? numberKeyboard.pressedColor
                  : styledBtn.hovered ? numberKeyboard.hoverColor
                  : styledBtn.isAccent ? numberKeyboard.accentColor
                  : numberKeyboard.normalColor

            border.color: styledBtn.isInvalid ? numberKeyboard.invalidTextColor
                        : styledBtn.hovered ? numberKeyboard.hoverBorderColor
                        : numberKeyboard.normalBorderColor

            border.width: numberKeyboard.borderWidth
            radius: numberKeyboard.borderRadius
        }

        contentItem: Text {
            text: styledBtn.text
            font.pixelSize: numberKeyboard.fontPixelSize
            color: styledBtn.isInvalid ? numberKeyboard.invalidTextColor
                  : styledBtn.isAccent ? numberKeyboard.accentTextColor
                  : numberKeyboard.fontColor
            anchors.fill: parent
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
        }

        onClicked: {
            if (styledBtn.isNumberKey) {
                numberKeyboard.handleNumberInput(styledBtn.text);
            } else if (styledBtn.isSymbolKey) {
                if (styledBtn.text === "-") {
                    if (numberKeyboard.isValueSelected) {
                        // 选中状态：直接替换为负号
                        numberKeyboard.currentValue = "-";
                        numberKeyboard.isValueSelected = false;
                    } else {
                        // 非选中状态：切换正负
                        numberKeyboard.currentValue = numberKeyboard.currentValue.startsWith("-")
                            ? numberKeyboard.currentValue.slice(1)
                            : "-" + numberKeyboard.currentValue;
                    }
                    numberKeyboard.displayText = numberKeyboard.currentValue;
                } else if (styledBtn.text === ".") {
                    if (numberKeyboard.currentValue.indexOf(".") === -1) {
                        if (numberKeyboard.isValueSelected) {
                            // 选中状态：替换为"0."
                            numberKeyboard.currentValue = "0.";
                            numberKeyboard.isValueSelected = false;
                        } else {
                            // 非选中状态：追加小数点
                            numberKeyboard.currentValue += ".";
                        }
                        numberKeyboard.displayText = numberKeyboard.currentValue;
                    }
                }
            }
        }
    }

    // 弹窗内容（核心：用Text替换TextField）
    contentItem: Column {
        anchors.fill: parent
        spacing: 15
        padding: 20
        width: parent.width

        // 提示区域（保持不变）
        Row {
            width: parent.width - 40
            spacing: 160

            Text {
                text: getLimitText()
                color: limitTextColor
                font.pixelSize: 30
                horizontalAlignment: Text.AlignLeft
                Layout.fillWidth: true
            }

            Text {
                visible: currentValue !== "" && !isValidValue(currentValue)
                text: qsTr("输入值超出范围")
                color: invalidTextColor
                font.pixelSize: 30
                horizontalAlignment: Text.AlignRight
                Layout.alignment: Qt.AlignRight | Qt.AlignVCenter
                Layout.maximumWidth: 150
            }
        }

        // 输入显示区（核心：用Text替代TextField）
        Rectangle {
            width: parent.width - 40
            height: 80
            // 选中状态时改变背景色（模拟选中视觉效果）
            color: isValueSelected ? selectedBackgroundColor : displayBackgroundColor
            border.color: "#e9ecef"
            border.width: 1
            radius: 8

            // 纯显示用的Text组件（无交互能力）
            Text {
                id: displayTextComp
                text: displayText || "0"  // 显示当前值（空值时显示0）
                font.pixelSize: displayFontSize
                color: fontColor
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                anchors.rightMargin: 15
                horizontalAlignment: Text.AlignRight
            }
        }

        // 数字按钮区域（保持不变）
        Column {
            spacing: 10
            width: 670
            anchors.horizontalCenter: parent.horizontalCenter

            Row { spacing: 10; width: parent.width; StyledButton { text: "7"; isNumberKey: true } StyledButton { text: "8"; isNumberKey: true } StyledButton { text: "9"; isNumberKey: true }}
            Row { spacing: 10; width: parent.width; StyledButton { text: "4"; isNumberKey: true } StyledButton { text: "5"; isNumberKey: true } StyledButton { text: "6"; isNumberKey: true }}
            Row { spacing: 10; width: parent.width; StyledButton { text: "1"; isNumberKey: true } StyledButton { text: "2"; isNumberKey: true } StyledButton { text: "3"; isNumberKey: true }}
            Row { spacing: 10; width: parent.width; StyledButton { text: "-"; isSymbolKey: true } StyledButton { text: "0"; isNumberKey: true } StyledButton { text: "."; isSymbolKey: true }}

            Row {
                spacing: 10
                width: parent.width

                StyledButton {
                    text: "清空"
                    isAccent: true
                    onClicked: {
                        currentValue = "";
                        displayText = "0";
                        isValueSelected = true;  // 清空后回到选中状态
                    }
                }

                StyledButton {
                    text: "⌫"
                    onClicked: {
                        if (currentValue.length > 0) {
                            currentValue = currentValue.slice(0, -1);
                            displayText = currentValue || "0";
                            // 退格后为空值时回到选中状态
                            isValueSelected = (currentValue === "");
                        }
                    }
                }

                StyledButton {
                    text: "确认"
                    isAccent: true
                    isInvalid: currentValue !== "" && !isValidValue(currentValue)
                    onClicked: {
                        var finalValue = currentValue || "0";
                        if (isValidValue(finalValue)) {
                            confirmed(finalValue);

                            if (activeInput) {
                                if (numberKeyboard.isDirectOverwrite) {
                                    activeInput.text = finalValue;
                                }
                                activeInput.isSelected = false;
                                activeInput.editingFinished(finalValue);
                                activeInput = null;
                            }

                            currentValue = "";
                            displayText = "0";
                            isValueSelected = true;
                            close();
                        }
                    }
                }
            }
        }
    }

    // 弹窗关闭时清理状态（保持不变）
    onClosed: {
        if (activeInput) {
            activeInput.isSelected = false;
            activeInput = null;
        }
        currentValue = "";
        displayText = "0";
        isValueSelected = true;
    }
}
